package com.e0box.game.logicGraphics.display
{
	import com.e0box.game.logicGraphics.Options;
	import com.e0box.game.logicGraphics.data.TileMap;
	
	import flash.utils.getTimer;
	
	import starling.display.QuadBatch;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	import utils.Random;
	
	public class Canvas extends QuadBatch
	{
		
		private var _map:TileMap;
		
		public function Canvas(width:uint, height:uint)
		{
			
			init();
		}
		
		public function init():void
		{
			_map = new TileMap(30, 20);
			var useTiles:Vector.<Tile> = Tile.getAllUseTiles();
			
			
			
			var start:Number = getTimer();
			
			this.reset();
			
			for each(var t:Tile in useTiles)
			{
				t.x = t.tileX * Options.TILE_SIZE;// + int(t.tileX / 4) * 1;
				t.y = t.tileY * Options.TILE_SIZE;// + int(t.tileY / 4) * 1;
				
				t.width = t.height = Options.TILE_SIZE;
				
				if(Random.boolean)
				{
					t.setState(Tile.STATE_BLANK);
				}
				else
				{
					t.setState(Tile.STATE_FLAG);
				}
				
				addImage(t);
			}
			
			trace(getTimer() - start);
			
			_map.getLeftTip();
			
			addEventListener(TouchEvent.TOUCH, onTouch);
		}
		
		private function onTouch(evt:TouchEvent):void
		{
			var touch:Touch = evt.getTouch(this);
			
			if(!touch) return;
			
			if(touch.phase == TouchPhase.BEGAN || touch.phase == TouchPhase.MOVED)
			{
				touch.getLocation(this, Options.activePoint);
				
				var tx:uint = uint(Options.activePoint.x / Options.TILE_SIZE);
				var ty:uint = uint(Options.activePoint.y / Options.TILE_SIZE);
				
				var t:Tile = _map.getTile(tx, ty);
				
				if(!t) return;
				
				if(t.getState() == Tile.STATE_FLAG)
				{
					t.setState(Tile.STATE_BLANK);
				}
				else
				{
					t.setState(Tile.STATE_FLAG);
				}
				
				
				
				this.reset();
				
				var useTiles:Vector.<Tile> = Tile.getAllUseTiles();
				for each(var t:Tile in useTiles)
				{
//					t.x = t.tileX * Options.TILE_SIZE + int(t.tileX / 4) * 1;
//					t.y = t.tileY * Options.TILE_SIZE + int(t.tileY / 4) * 1;
					
//					t.width = t.height = Options.TILE_SIZE;
					
//					if(Random.boolean)
//					{
//						t.setState(Tile.STATE_BLANK);
//					}
//					else
//					{
//						t.setState(Tile.STATE_FLAG);
//					}
					
					addImage(t);
				}
			}
		}
	}
}